import axios, { type AxiosInstance, type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { getApiBaseUrl, logEnvInfo } from './env'

// 打印环境信息
logEnvInfo()

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: getApiBaseUrl(),
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 从Pinia store获取token
    const userStore = useUserStore()
    const token = userStore.getToken()
    if (token && config.headers) {
      config.headers.Authorization = token
    }

    // 如果是FormData，删除Content-Type让浏览器自动设置
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type']
    }

    return config
  },
  (error) => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg, data } = response.data

    // 根据后端返回的状态码判断请求是否成功
    if (code === 200) {
      // 检查内层业务状态码
      if (data && typeof data === 'object' && data.code) {
        if (data.code === 401) {
          // 处理401未授权
          console.error('未授权，请重新登录')
          // 清除用户状态
          const userStore = useUserStore()
          userStore.logout()
          // 跳转到登录页
          window.location.href = '/login'
          return Promise.reject(new Error('未授权，请重新登录'))
        } else if (data.code !== 200) {
          // 处理其他业务错误
          console.error(data.message || '请求失败')
          return Promise.reject(new Error(data.message || '请求失败'))
        }
      }
      return data
    } else {
      // 处理HTTP错误
      console.error(msg || '请求失败')
      return Promise.reject(new Error(msg || '请求失败'))
    }
  },
  (error) => {
    console.error('Response Error:', error)

    if (error.response) {
      const { status, data } = error.response

      switch (status) {
        case 401:
          console.error('未授权，请重新登录')
          // 清除用户状态
          const userStore = useUserStore()
          userStore.logout()
          // 跳转到登录页
          window.location.href = '/login'
          break
        case 403:
          console.error('拒绝访问')
          break
        case 404:
          console.error('请求的资源不存在')
          break
        case 500:
          console.error('服务器内部错误')
          break
        default:
          console.error(data?.msg || '请求失败')
      }
    } else if (error.request) {
      console.error('网络错误，请检查网络连接')
    } else {
      console.error('请求配置错误')
    }

    return Promise.reject(error)
  }
)

// 封装GET请求
export const get = <T = any>(url: string, params?: any, config?: any): Promise<T> => {
  return service.get(url, { params, ...config })
}

// 封装POST请求
export const post = <T = any>(url: string, data?: any, config?: any): Promise<T> => {
  return service.post(url, data, config)
}

// 封装PUT请求
export const put = <T = any>(url: string, data?: any, config?: any): Promise<T> => {
  return service.put(url, data, config)
}

// 封装DELETE请求
export const del = <T = any>(url: string, config?: any): Promise<T> => {
  return service.delete(url, config)
}

// 封装上传请求
export const upload = <T = any>(url: string, file: File, config?: any): Promise<T> => {
  const formData = new FormData()
  formData.append('file', file)

  return service.post(url, formData, config)
}

export default service
